<template>
  <basic-container>
    <avue-crud
      :option="option"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :table-loading="loading"
      v-model="form"
      :search.sync="search"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @selection-change="selectionChange"
      :key="timer"
      :summary-method="summaryMethod"
    >
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" size="small" icon="el-icon-view" v-if="isHasPermission" @click="detailEvent(row)">详 情</el-button>
      </template>
      <template slot="lockedQuantity" slot-scope="{ row }">
        <div style="display: flex; justify-content: center" @click="handleLockQuantity(row)">
          <span style="color: blue">{{ row.lockedQuantity || 0 }}</span>
        </div>
      </template>
    </avue-crud>
    <el-dialog append-to-body :visible.sync="flagDialog" title="详情">
      <avue-crud ref="detailCrud" :option="optionDialog" :data="dataDialog" :table-loading="packDetailLoading">
        <template slot-scope="{ row }" slot="packSubType">
          <span>
            {{ row.packSubType === 'HISTORY_LABEL' ? '历史库存' : '正常' }}
          </span>
        </template>
        <!-- <template slot="menu" slot-scope="{ row }">
          <el-button @click="detailEvent2(row)" type="text" size="small" icon="el-icon-view">详 情</el-button>
        </template> -->
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="cancelDetailDialog()">取 消</el-button>
      </span>
      <!-- <el-dialog append-to-body :visible.sync="flagDialog2" title="SN详情">
        <avue-crud ref="snCrud" :option="optionDialog2" :data="dataDialog2" :table-loading="packDetailLoading2"> </avue-crud>
      </el-dialog> -->
    </el-dialog>
    <el-dialog append-to-body v-if="lockDialog" :visible.sync="lockDialog" title="备料数量锁定详情">
      <avue-crud
        ref="lockCrud"
        :option="lockOption"
        :data="lockData"
        :page.sync="lockPage"
        @search-reset="searchLockReset"
        @search-change="searchLockChange"
        @current-change="currentLockChange"
        @size-change="sizeLockChange"
        :table-loading="lockLoading"
      >
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-circle-close" @click="cancel()">取 消</el-button>
      </span>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-warehouse/material/page" :option="option" :page="page" :query="search" file-name="库存查询导出"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, areaInfo, update, remove, getSnData, getLockList, sumQuantity } from '@/api/warehouse/material';
import { mapGetters } from 'vuex';
import exportComp from '@/components/export-comp';

import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    let optionObj = {
      height: 'calc(100vh - 500px)',
      calcHeight: 30,
      delBtn: false,
      editBtn: false,
      addBtn: false,
      refreshBtn: false, //刷新按钮是否显示
      columnBtn: false, //控制表格列是否显示按钮是否显示
      border: true
    };
    return {
      pageCode: 'MATERIAL',
      form: {},
      search: {},
      query: {},
      loading: true,
      inventoryType: '',
      timer: new Date().getTime(),
      packDetailLoading: true,
      packDetailLoading2: true,
      lockLoading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      lockPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      lockQuery: {},
      params: {},
      selectionList: [],
      data: [],
      lockData: [],
      dataDialog: [],
      dataDialog2: [],
      lockDialog: false,
      flagDialog: false,
      flagDialog2: false,
      options: [],
      option: {
        height: 'calc(100vh - 440px)',
        columnBtn: false,
        calcHeight: 30,
        tip: false,
        searchMenuSpan: 4,
        refreshBtn: true, //刷新按钮是否显示
        searchBtn: true, // 显示查询的按钮
        searchSpan: 6,
        border: true,
        index: true,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        viewBtn: false,
        width: '100',
        searchLabelWidth: 100,
        searchMenuPosition: 'right',
        searchShow: true,
        indexLabel: '序号',
        menu: true,
        showSummary: true,
        column: [
          {
            label: '仓库类型',
            prop: 'inventoryType',
            type: 'select',
            searchOrder: 1,
            search: true,
            hide: true,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type',
            cascader: ['inventoryName'],
            searchOrder: 1
          },
          {
            label: '仓库名称',
            prop: 'inventoryName',
            search: true,
            filterable: true,
            searchOrder: 2,
            type: 'select',
            dicUrl: '/api/mes-admin/inventory/list?areaType=WAREHOUSE&inventoryType={{key}}',
            props: {
              label: 'name',
              value: 'id'
            },
            change: (val) => {
              this.findAreaInfo(val.value);
            },
            cascader: ['areaName']
          },
          {
            label: '储位编码',
            prop: 'areaCode'
          },
          {
            label: '储位名称',
            prop: 'areaName',
            search: true,
            searchOrder: 3,
            type: 'select',
            dicData: [],
            // dicUrl: '/api/mes-admin/area/select/inventory?inventoryId={{key}}',
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true,
            span: 4,
            searchOrder: 4
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料型号',
            prop: 'partMasterModel',
            search: true,
            searchOrder: 7
          },
          {
            label: '物料批次',
            prop: 'lotDate',
            search: true,
            searchOrder: 5
          },
          // {
          //   label: '供应商批次',
          //   prop: 'vendorLotNo',
          //   search: true
          // },
          // {
          //   label: 'D/C',
          //   prop: 'lotNo'
          // },
          {
            label: '品牌',
            prop: 'materialBrand'
          },
          {
            label: '物料数量',
            prop: 'totalQuantity',
            type: 'number',
            precision: 10
          },
          {
            label: '锁定数量',
            prop: 'lockedQuantity'
          },
          // {
          //   label: '报废数量',
          //   prop: 'scrapQuantity'
          // },
          {
            label: '可用数量',
            prop: 'quantity'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo',
            search: true,
            hide: true,
            searchOrder: 6
          }
          // {
          //   label: '包装数',
          //   prop: 'packs'
          // }
        ]
      },
      optionDialog: {
        ...optionObj,
        menuWidth: 100,
        menu: false, //表格操作栏是否显示
        column: [
          {
            label: '包装',
            prop: 'sequenceNumber',
            span: 6
          },
          {
            label: '包装数量',
            prop: 'packQuantity',
            span: 6
          },
          {
            label: '物料批次',
            prop: 'lotDate',
            span: 6
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          {
            label: '检验批次',
            prop: 'inspectionLotNo'
          },
          {
            label: 'D/C',
            prop: 'dateCode'
          },
          {
            label: '品牌',
            prop: 'materialBrand'
          },
          {
            label: '供应商编码',
            prop: 'vendorCode',
            span: 6
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          {
            label: '库存类型',
            prop: 'packSubType'
          },
          {
            label: '生产日期',
            prop: 'vendorDate'
          },
          {
            label: '入库时间',
            prop: 'packTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            searchRange: true,
            span: 4
          },
          {
            label: '状态',
            prop: 'packStatus',
            searchLabelWidth: 90,
            span: 4,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=pack_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
            // dicFormatter: (data) => {
            //   console.log(data, 33333333333);
            //   return;
            // }
          }
        ]
      },
      optionDialog2: {
        ...optionObj,
        menu: false, //表格操作栏是否显示
        column: [
          {
            label: 'SN包装',
            prop: 'sequenceNumber'
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 6
          },
          {
            label: '生成日期',
            prop: 'packedDate'
          },
          {
            label: '状态',
            prop: 'packStatus',
            searchLabelWidth: 90,
            span: 4,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=pack_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          }
        ]
      },
      lockOption: {
        ...optionObj,
        searchLabelWidth: 100,
        searchMenuPosition: 'right',
        menu: false,
        column: [
          {
            label: '备料单号',
            prop: 'sheetNo',
            searchSpan: 8,
            search: true
          },
          {
            label: '需求数量',
            prop: 'quantityRequired'
          },
          {
            label: '锁定数量（应发数量）',
            prop: 'quantityLocked'
          },
          {
            label: '最小包规',
            prop: 'miniPackQuantity'
          },
          {
            label: '超发数量',
            prop: 'quantityOverissued'
          },
          {
            label: '关联工单号',
            prop: 'workOrderNoStr'
          },
          {
            label: '关联领料单号',
            prop: 'roSheetNoStr'
          }
        ]
      },
      lockedQuantity: '',
      quantity: '',
      totalQuantity: ''
    };
  },
  filters: {
    statusConvert(val) {
      switch (val) {
        case 1:
          return '正常';
        case 2:
          return '全部锁定';
        case 3:
          return '部分锁定';
        case 4:
          return '报废';
        case 5:
          return '已出库';
        case 6:
          return '已入库';
        default:
          break;
      }
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.material_view, false),
        addBtn: this.vaildData(this.permission.material_add, false),
        delBtn: this.vaildData(this.permission.material_delete, false),
        editBtn: this.vaildData(this.permission.material_edit, false)
      };
    },
    isHasPermission() {
      return this.permission.material_detail;
      //库存原材料 和 库存成品 共用一个页面。但是菜单编码是唯一值，所以在此区分
      // if (this.$route.path === '/warehouse/material/1') {
      //   return this.permission.material_view;
      // } else if (this.$route.path === '/warehouse/material/2') {
      //   return this.permission.product_view;
      // } else if (this.$route.path === '/warehouse/material/3') {
      //   return this.permission.line_view;
      // }
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    summaryMethod({ columns, data }) {
      console.log(columns, 'columns1111');
      let sums = [];
      if (columns.length > 0) {
        columns.forEach((column, index) => {
          console.log(column, 'column222');
          let prop = column.property;
          if (['totalQuantity', 'lockedQuantity', 'quantity'].includes(prop)) {
            if (prop === 'totalQuantity') {
              sums[index] = this.totalQuantity;
            }
            if (prop === 'lockedQuantity') {
              sums[index] = this.lockedQuantity;
            }
            if (prop === 'quantity') {
              sums[index] = this.quantity;
            }
          } else if (prop === 'areaCode') {
            sums[index] = '合计';
          } else {
            sums[index] = '';
          }
        });
      }
      console.log(sums, 'sums');
      return sums;
    },
    findAreaInfo(inventoryId) {
      areaInfo(inventoryId).then((res) => {
        let data = res.data.data;
        let areaName = this.findObject(this.option.column, 'areaName');
        areaName.dicData = data;
        console.log(areaName, 8888, data);
      });
    },
    cancelDetailDialog() {
      this.flagDialog = false;
    },
    cancel() {
      this.lockDialog = false;
    },
    handleLockQuantity(row) {
      this.lockDialog = true;
      this.lockPage = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
      this.lockQuery = {
        lotNo: row.lotNo,
        inventoryId: row.inventoryId,
        areaId: row.areaId,
        partMasterId: row.partMasterId
      };
      this.onLockLoad(this.lockPage, this.lockQuery);
    },
    searchLockReset(params, done) {
      this.lockPage.currentPage = 1;
      this.lockPage.pageSize = 15;
      this.onLockLoad(this.lockPage);
      done();
    },
    searchLockChange(params, done) {
      this.onLockLoad(this.lockPage, params);
      done();
    },
    currentLockChange(currentPage) {
      this.lockPage.currentPage = currentPage;
      this.onLockLoad(this.lockPage);
    },
    sizeLockChange(pageSize) {
      this.lockPage.pageSize = pageSize;
      this.onLockLoad(this.lockPage);
    },
    detailEvent(row) {
      this.flagDialog = true;
      getDetail({
        areaId: row.areaId,
        inventoryId: row.inventoryId,
        lotNo: row.lotNo,
        partMasterId: row.partMasterId,
        lotDate: row.lotDate
      }).then((res) => {
        this.packDetailLoading = true;
        if (res.data.data) {
          this.dataDialog = res.data.data.map((item) => {
            item.packStatus = String(item.packStatus);
            return item;
          });
          this.packDetailLoading = false;
        }
      });
    },
    detailEvent2(row) {
      this.flagDialog2 = true;
      getSnData(row.id).then((res) => {
        this.packDetailLoading2 = true;
        if (res.data.data) {
          this.dataDialog2 = res.data.data.map((item) => {
            item.packStatus = String(item.packStatus);
            return item;
          });
          this.packDetailLoading2 = false;
        }
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset(params, done) {
      this.query = {};
      this.page.currentPage = 1;
      this.page.pageSize = 15;
      this.onLoad(this.page, this.query);
    },
    searchChange(params, done) {
      if (params.createTime) {
        params.startDate = params.createTime[0];
        params.endDate = params.createTime[1];
        delete query.createTime;
      }
      if (params.inventoryName) {
        params.inventoryId = params.inventoryName;
        delete params.inventoryName;
      }
      if (params.areaName) {
        params.areaId = params.areaName;
        delete params.areaName;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.params);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records || [];
        this.loading = false;
        this.collect(Object.assign(params, this.query));
      });
    },
    collect(params) {
      sumQuantity(params).then((res) => {
        this.lockedQuantity = res.data.data.lockedQuantity;
        this.quantity = res.data.data.quantity;
        this.totalQuantity = res.data.data.totalQuantity;
      });
    },
    onLockLoad(page, params = {}) {
      this.lockLoading = true;
      getLockList(page.currentPage, page.pageSize, Object.assign(params, this.lockQuery)).then((res) => {
        const data = res.data.data;
        this.lockPage.total = data.total;
        this.lockData = data.records || [];
        this.lockLoading = false;
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  watch: {}
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__body {
  padding: 15px 24px;
  .avue-crud__menu {
    display: none;
  }
}
</style>
